import axios from 'axios';
import md5 from 'js-md5';
import env from '@/config/env.js'
import util from '@/common/util.js'
import Vue from 'vue';
const service = axios.create({
	withCredentials: true,
	crossDomain: true,
	baseURL: env[env.mchType].baseUrl,
	timeout: 6000
})
// request拦截器,在请求之前做一些处理
service.interceptors.request.use(
	config => {
		var timestamp = new Date().getTime();
		var signToken = util.getLocalCache('token');
		let headers = {
			"role": "EMP",
			"platid": env[env.mchType].platid,
			"mchid": env[env.mchType].mchid,
			"type": env.type,
			"authority": 0,
			"timestamp": timestamp,
			"authorization": signToken,
			"sign": md5(timestamp + signToken + "open@2023@vdigit"),
			"Content-Type": 'application/x-www-form-urlencoded'
		}
		config.headers = {
			...headers,
			...config.headers
		}
		return config;
	},
	error => {
		return Promise.reject(error);
	}
);

//配置成功后的拦截器
service.interceptors.response.use(res => {
	uni.hideLoading()
	if (res.status == 200) {
		if (res.data.code == 200) {
			return res.data.data
		} else if (res.data.code == 500203) {
			uni.showToast({
				title: res.data.msg,
				icon: 'none'
			})
			// uni.navigateTo({
			// 	url: '/pages/login/login'
			// })
		} else if (res.data.code == 401) {
			uni.showToast({
				title: '登录已过期，请重新登录',
				icon: 'none'
			})
			uni.removeStorageSync('token')
			let timer = setTimeout(() => {
				clearTimeout(timer)
				uni.redirectTo({
					url: '/pages/login/login'
				})
			}, 500)
		} else {
			uni.showToast({
				title: res.data.msg,
				icon: 'none'
			})
			return Promise.reject(res.data.msg);
		}
	} else {
		return Promise.reject(res.data.msg);
	}
}, error => {
	// uni.hideLoading()
	return Promise.reject(error)
})

axios.defaults.adapter = function(config) { //自己定义个适配器，用来适配uniapp的语法
	if (config.loadData) {
		uni.showLoading({
			title: config?.loadData?.title || "加载中...",
			mask: true
		})
	}
	return new Promise((resolve, reject) => {
		var settle = require('axios/lib/core/settle');
		var buildURL = require('axios/lib/helpers/buildURL');
		uni.request({
			method: config.method.toUpperCase(),
			url: config.baseURL + buildURL(config.url, config.params, config.paramsSerializer),
			header: config.headers,
			data: config.data,
			dataType: config.dataType,
			responseType: config.responseType,
			sslVerify: config.sslVerify,
			complete: function complete(response) {
				response = {
					data: response.data,
					status: response.statusCode,
					errMsg: response.errMsg,
					header: response.header,
					config: config
				};
				settle(resolve, reject, response);
			}
		})
	})
}
export default service